<template>
  <el-card shadow="never">
    <template #header>
      <el-form label-width="80px">
        <el-row :gutter="10">
          <el-col :span="6" :xs="24">
            <el-form-item label="机构名称">
              <el-select style="width: 100%" v-model="page.institutionId" clearable filterable>
                <el-option v-for="item in institutionList" :key="item.name" :label="item.name"
                           :value="item.institutionId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label="状态">
              <el-select style="width: 100%" v-model="page.status" clearable>
                <el-option :value="1" label="启用"></el-option>
                <el-option :value="0" label="禁用"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10" :xs="24">
            <el-form-item label="创建时间">
              <el-date-picker
                  style="width: 100%"
                  v-model="page.createTimeValue"
                  type="daterange"
                  range-separator="~"
                  value-format="x"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label-width="20px">
              <el-button type="primary" @click="getTableData">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <div style="text-align: right;margin-bottom: 10px;line-height: 32px">
      <span style="color: #409eff;float: left;font-size: 18px">授信总额度 : {{ moneyTotal }}</span>
      <el-button type="primary" icon="el-icon-plus" @click="addInstitution">添加机构</el-button>
    </div>
    <Table :tableColumn="tableColumn" :tableData="tableData" :page="page"
           @handleCurrentChange="(val)=>{page.pageNum = val,getTableData()}"
           @handleSizeChange="(val)=>{page.pageSize = val,getTableData()}"
    >
      <template #url="{row}">
        <el-image v-if="row.businessLicense" style="width: 80px;height: 80px" :src="row.businessLicense"
                  :preview-src-list="[row.businessLicense]"></el-image>
      </template>
      <template #status="{row}">
        <el-switch :model-value="row.status === 1" @change="switchChange(row)"></el-switch>
      </template>
      <template #handle="{row}">
        <el-button type="text" @click="editInstitution(row)">编辑</el-button>
        <el-button type="text" @click="resetPassword(row)">重置密码</el-button>
      </template>
    </Table>

    <Dialog v-model="visible.isShow" :title="visible.title" @cancel="visible.isShow = false"
            @close="clearInstitution"
            @confirm="institutionConfirm"
    >
      <el-form label-width="100px" ref="form" :model="institutionForm" :rules="institutionRulesForm">
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="institutionForm.name"/>
        </el-form-item>
        <el-form-item label="机构账号" prop="account">
          <el-input v-model="institutionForm.account"/>
        </el-form-item>
        <el-form-item label="机构电话" prop="companyPhone">
          <el-input v-model="institutionForm.companyPhone"/>
        </el-form-item>
        <el-form-item label="机构地址" prop="companyAddress">
          <el-input v-model="institutionForm.companyAddress"/>
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              action="#"
              ref="upload"
              accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG"
              :http-request="uploadChange"
          >
            <i v-if="!institutionForm.businessLicense" class="el-icon-plus avatar-uploader-icon"></i>
            <img v-else style="width: 100%;height: 100%" :src="institutionForm.businessLicense">
          </el-upload>
        </el-form-item>
        <el-form-item label="证件代码" prop="identificationCode">
          <el-input v-model="institutionForm.identificationCode"/>
        </el-form-item>
        <el-form-item label="法人" prop="legalPerson">
          <el-input v-model="institutionForm.legalPerson"/>
        </el-form-item>
        <el-form-item label="法人证件" prop="legalPersonCertificate">
          <el-input v-model="institutionForm.legalPersonCertificate"/>
        </el-form-item>
        <el-form-item label="法人电话" prop="legalPersonPhone">
          <el-input v-model="institutionForm.legalPersonPhone"/>
        </el-form-item>
        <el-form-item label="授信额度" prop="lineOfCredit">
          <el-input v-model="institutionForm.lineOfCredit"/>
        </el-form-item>
      </el-form>
    </Dialog>
  </el-card>
</template>

<script>
import {reactive, toRefs, ref, onMounted} from 'vue'
import {uploadImage} from "@/api";
import {
  insertInstitution,
  updateInstitution,
  fetchInstitution,
  resetPasswordInstitution,
  updateStatusInstitution,
  fetchMoneyTotal
} from '@/api/institution'
import {selectInstitution} from "@/api";
import {ElMessage, ElMessageBox} from "element-plus";
import {dateFormatTimeStamp} from "@/utils";

const tableColumn = [
  {label: '机构名称', prop: 'name', align: 'center', minWidth: 100},
  {label: '机构账号', prop: 'account', align: 'center', minWidth: 100},
  {label: '授信额度', prop: 'lineOfCredit', align: 'center', minWidth: 100},
  {label: '电话', prop: 'companyPhone', align: 'center', minWidth: 100},
  {label: '地址', prop: 'companyAddress', align: 'center', minWidth: 100},
  {label: '营业执照', prop: 'businessLicense', slot: 'url', align: 'center', minWidth: 100},
  {label: '证件代码', prop: 'identificationCode', align: 'center', minWidth: 100},
  {label: '法人', prop: 'legalPerson', align: 'center', minWidth: 100},
  {label: '法人证件', prop: 'legalPersonCertificate', align: 'center', minWidth: 100},
  {label: '法人电话', prop: 'legalPersonPhone', align: 'center', minWidth: 100},
  {label: '状态', prop: 'status', align: 'center', slot: 'status', minWidth: 100},
  {label: '创建时间', prop: 'creationTime', align: 'center', minWidth: 150},
  {label: '创建人', prop: 'inputName', align: 'center', minWidth: 100},
  {label: '操作', slot: 'handle', align: 'center', fixed: 'right', minWidth: 150},
]
export default {
  name: "InstitutionList",
  setup() {
    const form = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableData: [],
      visible: {
        isShow: false,
        type: 'add',
        title: '新增'
      },
      institutionList: [],
      institutionForm: {},
      institutionRulesForm: {
        name: [
          {required: true, message: '请输入机构名称', trigger: 'blur'}
        ],
        account: [
          {required: true, message: '请输入机构账号', trigger: 'blur'}
        ]
      },
      moneyTotal: 0
    })
    const methods = {
      async getTableData() {
        const [datetimeStart, datetimeEnd] = dateFormatTimeStamp(state.page.createTimeValue)
        const params = {
          datetimeStart, datetimeEnd,
          ...state.page
        }
        delete params.createTimeValue
        methods.getTotal(params)
        const res = await fetchInstitution(params)
        if (res.code === 200) {
          const {list, total} = res.data
          state.tableData = list
          state.page = {
            ...state.page,
            total
          }
        }
      },
      async getTotal(params) {
        const res = await fetchMoneyTotal(params)
        if (res.code === 200) {
          state.moneyTotal = res.data
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0,
        }
        methods.getTableData()
      },
      clearInstitution() {
        state.institutionForm = {}
        form.value.resetFields()
      },
      getSelect() {
        selectInstitution().then(res => {
          state.institutionList = res.data
        })
      },
      editInstitution(row) {
        state.institutionForm = {
          ...row
        }
        state.visible = {
          isShow: true,
          type: 'edit',
          title: '编辑机构'
        }
      },
      // 上传图片
      async uploadChange(data) {
        const formData = new FormData()
        formData.append('file', data.file)
        formData.append('type', 1)
        const res = await uploadImage(formData)
        if (res.code === 200) {
          state.institutionForm.businessLicense = res.data
        }
      },
      resetPassword(row) {
        ElMessageBox.confirm('确认进行此操作?', '提示', {
          type: 'warning',
        }).then(async () => {
          const {institutionId} = row
          const res = await resetPasswordInstitution({
            institutionId
          })
          if (res.code === 200) {
            ElMessage.success({
              message: '重置成功'
            })
            methods.getMenuData()
          }
        }).catch(() => {

        });
      },
      async switchChange({institutionId, status}) {
        const res = await updateStatusInstitution({
          id: institutionId,
          status: status === 1 ? 0 : 1
        })
        if (res.code === 200) {
          ElMessage.success('操作成功')
          methods.getTableData()
        }
      },
      addInstitution() {
        state.visible = {
          isShow: true,
          type: 'add',
          title: '添加机构'
        }
      },
      institutionConfirm() {
        form.value.validate(async v => {
          if (v) {
            const isAdd = state.visible.type === 'add'
            const api = ((params) => isAdd ? insertInstitution(params) : updateInstitution(params))
            const res = await api({
              ...state.institutionForm,
              lineOfCredit: parseFloat(state.institutionForm.lineOfCredit) || null
            })
            if (res.code === 200) {
              state.visible.isShow = false
              ElMessage.success(isAdd ? '添加成功' : '编辑成功')
              methods.getTableData()
            }
          }
        })
      }
    }
    onMounted(() => {
      methods.getTableData()
      methods.getSelect()
    })
    return {
      form,
      ...toRefs(state),
      tableColumn,
      ...methods
    }
  }
}
</script>

<style scoped>

</style>
